/**
 * plugins/index.js
 *
 * Automatically included in `./src/main.js`
 */

// Plugins
import vuetify from './vuetify'
import router from '@/router'
import axios from 'axios'
import { createApp, h, ref as vueRef } from 'vue'
import { VSnackbar } from 'vuetify/components'

export function registerPlugins (app) {
  app
    .use(vuetify)
    .use(router)
}

// 添加全局 axios 请求拦截器，自动带上 token
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
}, error => Promise.reject(error))

let logoutSnackbar = null
function showLogoutSnackbar(msg) {
  if (logoutSnackbar) return
  const container = document.createElement('div')
  document.body.appendChild(container)
  const visible = vueRef(true)
  const app = createApp({
    setup() {
      return () => h(VSnackbar, {
        modelValue: visible.value,
        'onUpdate:modelValue': val => { visible.value = val },
        color: 'error',
        timeout: 3000,
        location: 'top',
      }, { default: () => msg || '登录状态已失效，请重新登录' })
    }
  })
  logoutSnackbar = app.mount(container)
  setTimeout(() => {
    visible.value = false
    setTimeout(() => {
      app.unmount()
      document.body.removeChild(container)
      logoutSnackbar = null
      localStorage.removeItem('token')
      window.location.href = '/login'
    }, 300)
  }, 3000)
}

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      if (window.location.pathname === '/login') {
        localStorage.removeItem('token')
        return Promise.reject(error)
      }
      const msg = error.response.data?.message || '登录状态已失效，请重新登录'
      if (window.__showGlobalDialog) {
        window.__showGlobalDialog(msg, () => {
          localStorage.removeItem('token')
          window.location.href = '/login'
        })
      } else {
        localStorage.removeItem('token')
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)
